﻿using System.Linq;
using System.Web.Mvc;

using DAL;

using App.Models;

namespace App.Controllers
{

    [HandleError]
    public class AccountController : BaseController
    {
        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                AccountMembershipService MembershipService = new AccountMembershipService();
                var person = MembershipService.ValidateUser(model.UserName, model.Password);
                if (person != null && !string.IsNullOrWhiteSpace(person.Id) && person.Id.Length == 36)
                {
                    Session["person"] = person;
                    return Redirect("../Home/Index");
                }
            }
            ModelState.AddModelError("UserName", "用户名或者密码出错。");
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View();  
        }

        public ActionResult LogOff()
        {

            if (Session["person"] != null)
            {
                Session["person"] = null;

            }
            return RedirectToAction("Logon", "Account");
        }


        [HttpPost]
        public ActionResult ChangePassword(string id)
        {
            if (Session["person"] != null && !string.IsNullOrEmpty(id))
            {
                var person = (SysPerson)Session["person"];
                using (SysEntities army = new SysEntities())
                {
                    var per = army.SysPerson.FirstOrDefault(s => s.Id == person.Id);
                    per.Password = id;

                    army.SaveChanges();
                    //记录日志
                }
                return Content("成功");
            }
            else
            {
                return RedirectToAction("Logon", "Account");
            }
        }

    }

}
